package com.example.demo.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * <h3>reqister</h3>
 * <p>测试</p>
 *
 * @author : chenjunjie
 * @date : 2021-06-26 09:48
 **/
@RestController
public class LoginController {

    /**
     * 后台登陆
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public Map get(String username, String password){
        Map<String,String> map = null;
        System.out.println("接收的信息"+username+password);
        String  url="http://127.0.0.1:8080/oauth/token?";
        String client_id = "admin";
        String client_secret="112233";
        String grant_type="password";

        String params ="username="+username+"&password="+password+"&client_id=" + client_id + "&client_secret=" + client_secret  + "&grant_type=" + grant_type;

        RestTemplate restTemplate = new RestTemplate();
        try {
            map =restTemplate.getForObject(url+params, Map.class);
            map.put("username",username);
        }catch (HttpClientErrorException e){
            e.getMessage();
            map=new HashMap<>(5);
            map.put("status", HttpStatus.BAD_REQUEST.value()+"");
            map.put("message", e.getMessage());
            return  map;
        }
        return map;
    }

    /**
     * 微信登陆，为测试
     * @param code
     * @return
     */
    @RequestMapping("wxLogin")
    public Map Login(String code){

        Map map = new HashMap();
        //登录凭证不能为空
        if (code == null || code.length() == 0) {
            map.put("status", 0);
            map.put("msg", "code 不能为空");
            return map;
        }
        String url=" https://api.weixin.qq.com/sns/jscode2session?";
        //小程序唯一标识   (在微信小程序管理后台获取)
        String wxspAppid = "wx7e37ddfea6ed378c";
        //小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = "3a4207d34973302567b27a46b9e57e65";
        //授权（必填）
        String grant_type = "authorization_code";

        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;

        RestTemplate restTemplate=new RestTemplate();
        String str=restTemplate.getForObject(url+params,String.class);

        ObjectMapper obMapper=new ObjectMapper();
        Map<String,Object> map1=obMapper.convertValue(str,Map.class);

        String session_key = map1.get("session_key").toString();
        String openid= map1.get("openid").toString();


        return map;

    }


}
